package common

import (
	"fmt"
	"go_gin_gorm_oceanlearn_study/model"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	"github.com/spf13/viper"
)

var DB *gorm.DB

//初始化数据库
func InitDB() *gorm.DB{
	//连接数据库
	host := viper.GetString("datasource.host")
	port := viper.GetString("datasource.port")
	user := viper.GetString("datasource.user")
	dbname := viper.GetString("datasource.dbname")
	password := viper.GetString("datasource.password")
	sslmode := viper.GetString("datasource.sslmode")
	TimeZone := viper.GetString("datasource.TimeZone")

	psqlInfo := fmt.Sprintf("host=%s port=%s user=%s dbname=%s "+
		"password=%s sslmode=%s TimeZone=%s",
		host, port, user, dbname, password, sslmode, TimeZone)

	// db, err := gorm.Open("postgres", "host=localhost port=5432 user=postgres dbname=oceanLearn password=97301335 sslmode=disable TimeZone=Asia/Shanghai")
	db, err := gorm.Open("postgres", psqlInfo)
	if err != nil {
		panic(err)
	}
	
	// 禁用默认表名的复数形式，如果置为 true，则 `User` 的默认表名是 `user`
	db.SingularTable(true)

	// 绑定表
	db.AutoMigrate(&model.User{})

	DB = db  //获取DB
	return db
}

//获取DB实例
func GetDB() *gorm.DB {
	return DB
}